package blogger.client.ui.panels;

import java.util.LinkedList;
import java.util.List;

import blogger.client.async.Callback;
import blogger.client.async.GetTwitsResponse;
import blogger.client.async.services.TwitService;
import blogger.client.async.services.TwitServiceAsync;
import blogger.client.async.services.UserService;
import blogger.client.async.services.UserServiceAsync;
import blogger.client.eventqueqe.events.TwitAddedEvent;
import blogger.client.eventqueqe.events.TwitDeletedEvent;
import blogger.client.eventqueqe.handlers.TwitAddingHandler;
import blogger.client.eventqueqe.handlers.TwitDeletingHandler;
import blogger.client.model.entity.Message;
import blogger.client.model.entity.User;
import blogger.client.ui.widgets.TwitView;

import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;


public class AnyTwitsPanel extends SlidePanel {
    private long currentUserId = 0;

    private List<Message> model = new LinkedList<Message>();

    final TwitServiceAsync twitServiceAsync = TwitService.App.getInstance();
    final UserServiceAsync userServiceAsync = UserService.App.getInstance();

    private HandlerManager eventBus;

    public AnyTwitsPanel(boolean b, HandlerManager eventBus) {
        super(b);
        this.sinkEvents(Event.ONCLICK);
        this.eventBus = eventBus;
        this.setStyleName("slide");
        this.init();
    }

    private void init(){
        userServiceAsync.getCurrentUserId(new Callback<Long>() {
            @Override
            public void doResult(Long result) {
                currentUserId = result;
            }
        });
        this.fillTwitsPanel();
        this.listenForTwits();
        this.startTimer();
    }

    public void listenForTwits() {
        eventBus.addHandler(TwitAddedEvent.TYPE, new TwitAddingHandler() {
            //@Override
            public void onTwitAdded(final TwitAddedEvent e) {
                UserService.App.getInstance().getUserById(
                        e.getMessage().getUser_id(), new Callback<User>() {
                            @Override
                            public void doResult(User result) {
                                AnyTwitsPanel.this.insert(new TwitView(result, e.getMessage(),eventBus,currentUserId),1);
                                model.add(0,e.getMessage());
                            }
                        });
            }
        });

        eventBus.addHandler(TwitDeletedEvent.TYPE, new TwitDeletingHandler() {
            //@Override
            public void onTwitDeleted(TwitDeletedEvent e) {
//                Window.alert("here " + currentUserId);
                AnyTwitsPanel.this.remove(e.getTwitView());
                model.remove(e.getTwitView().getModelMessage());
            }
        });
    }


    private Timer timer = new Timer() {
        @Override
        public void run() {
            if(currentUserId != 0){
                twitServiceAsync.lastTwits(model.get(0).getDate(),new Callback<GetTwitsResponse>() {
                    @Override
                    public void doResult(GetTwitsResponse result) {
                        if(result != null){
                            List<Message> messages = result.getMessages();
                            List<User> users = result.getUsers();
                            int size = messages.size();
                            for(int i=0; i<size; ++i){
                                if(messages.get(i).getUser_id() != currentUserId){
                                    AnyTwitsPanel.this.insert(new TwitView(users.get(i),messages.get(i),eventBus,currentUserId),1);
                                    model.add(0,messages.get(i));
                                }
                            }
                        }
                    }
                });
            }
        }
    };

    public void fillTwitsPanel(){
        twitServiceAsync.getTwits(new Callback<GetTwitsResponse>() {
            @Override
            public void doResult(GetTwitsResponse result) {
                if(result != null){
                    List<Message> messages = result.getMessages();
                    List<User> users  = result.getUsers();
                    int size = messages.size();
                    for(int i=0; i<size; ++i){
                        AnyTwitsPanel.this.add(new TwitView(users.get(i),messages.get(i),eventBus,currentUserId));
                        model.add(messages.get(i));
                    }
                }
            }
        });
    }

    private void startTimer(){
        timer.scheduleRepeating(10000);
    }

    private void stopTimer(){
        timer.cancel();
    }
}



